package com.bai.localshop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bai.localshop.context.BaseContext;
import com.bai.localshop.exception.BaseException;
import com.bai.localshop.mapper.ProductMapper;
import com.bai.localshop.mapper.ShoppingCartMapper;
import com.bai.localshop.pojo.dto.SaveShoppingCartDTO;
import com.bai.localshop.pojo.entity.Product;
import com.bai.localshop.pojo.entity.ShoppingCart;
import com.bai.localshop.pojo.vo.ShoppingCartVO;
import com.bai.localshop.service.ShoppingCartService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.bai.localshop.constant.SystemConstants.*;

@Service
@RequiredArgsConstructor
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    private final ProductMapper productMapper;
    private final ShoppingCartMapper shoppingCartMapper;

    /**
     * 添加购物车
     *
     * @param requestParam
     */
    @Override
    public void save(SaveShoppingCartDTO requestParam) {
        //判断是否购物车已有这条商品的数据，如果有就数量增加，没有就新插入一条购物车数据
        Integer quantity = requestParam.getQuantity();
        Long productId = requestParam.getProductId();
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper1 = Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getProductId, productId)
                .eq(ShoppingCart::getUserId, userId);
        ShoppingCart shoppingCartDB = shoppingCartMapper.selectOne(queryWrapper1);
        if (shoppingCartDB != null) {
            //执行添加操作之前判断当前商品状态是否正常
            if (shoppingCartDB.getQuantity() > 0) {
                Product productDB = productMapper.selectById(shoppingCartDB.getProductId());

                if (productDB == null) {
                    shoppingCartDB.setStatus(PRODUCT_DELETED);
                    shoppingCartMapper.updateById(shoppingCartDB);
                    throw new BaseException("商品已删除");
                }
                if (productDB.getStock() <= 0) {
                    shoppingCartDB.setStatus(PRODUCT_INSUFFICIENT_STOCK);
                    shoppingCartMapper.updateById(shoppingCartDB);
                    throw new BaseException("商品库存不足");
                } else if (productDB.getStatus() == PRODUCT_OFFLINE) {
                    shoppingCartDB.setStatus(PRODUCT_OFFLINE);
                    shoppingCartMapper.updateById(shoppingCartDB);
                    throw new BaseException("商品已下架");
                }
                //数量+1
                LambdaUpdateWrapper<ShoppingCart> updateWrapper = Wrappers.lambdaUpdate(ShoppingCart.class)
                        .set(ShoppingCart::getQuantity, shoppingCartDB.getQuantity() + quantity)
                        .eq(ShoppingCart::getProductId, productId);
                int update = shoppingCartMapper.update(updateWrapper);
                if (update < 1) {
                    throw new BaseException("添加购物车失败");
                }
            }
        } else {
            //新增购物车数据
            LambdaQueryWrapper<Product> queryWrapper = Wrappers.lambdaQuery(Product.class)
                    .eq(Product::getId, productId);
            Product product = productMapper.selectOne(queryWrapper);
            
            // 检查商品是否存在
            if (product == null) {
                throw new BaseException("商品不存在");
            }

            Long price = product.getPrice();
            ShoppingCart shoppingCart = ShoppingCart.builder()
                    .userId(userId)
                    .productId(product.getId())
                    .quantity(quantity)
                    .unitPrice(price)
                    .totalAmount(price * quantity)
                    .productName(product.getName())
                    .productImage(product.getImage())
                    .status(product.getStatus())
                    .createTime(LocalDateTime.now())
                    .createUser(userId)
                    .updateTime(LocalDateTime.now())
                    .updateUser(userId)
                    .build();

            int insert = shoppingCartMapper.insert(shoppingCart);
            if (insert < 1) {
                throw new BaseException("添加购物车失败");
            }
        }
    }

    /**
     * 查看购物车
     *
     * @return
     */
    @Override
    public List<ShoppingCartVO> queryList() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId);
        // 查询到商品状态如果为已下架或者库存为0，在购物车给出对应提示
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(queryWrapper);
        if (shoppingCarts.isEmpty()) {
            return Collections.emptyList();
        }
        List<Long> productIds = shoppingCarts.stream()
                .map(ShoppingCart::getProductId)
                .distinct()
                .toList();

        Map<Long, Product> productMap = productMapper.selectBatchIds(productIds).stream()
                .collect(Collectors.toMap(
                        Product::getId,//键存入商品id
                        Function.identity()));//值存入商品本身

        // 更新购物车中商品的状态
        for (ShoppingCart cart : shoppingCarts) {
            Product product = productMap.get(cart.getProductId());
            if (product == null) {
                // 商品已删除
                cart.setStatus(PRODUCT_DELETED);
                shoppingCartMapper.updateById(cart);
                continue;
            }
            // 根据商品实际状态更新购物车中的状态
            if (product.getStatus() == PRODUCT_OFFLINE) {
                // 商品已下架
                cart.setStatus(PRODUCT_OFFLINE);
                shoppingCartMapper.updateById(cart);
            } else if (product.getStock() <= 0) {
                // 商品库存不足
                cart.setStatus(PRODUCT_INSUFFICIENT_STOCK);
                shoppingCartMapper.updateById(cart);
            } else if (cart.getStatus() != PRODUCT_NORMAL) {
                // 商品恢复正常状态
                cart.setStatus(PRODUCT_NORMAL);
                shoppingCartMapper.updateById(cart);
            }
        }

        return BeanUtil.copyToList(shoppingCarts, ShoppingCartVO.class);
    }

    /**
     * 清空购物车
     */
    @Override
    public void cleanById() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> deleteWrapper = Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId);
        shoppingCartMapper.delete(deleteWrapper);
    }

    /**
     * 删除一个商品
     */
    @Override
    public void reduceById(Long id) {
        //判断当前商品的数量，如果为1就删除购物车中的商品，如果大于1就数量-1
        ShoppingCart shoppingCart = shoppingCartMapper.selectById(id);
        Long userId = BaseContext.getCurrentId();
        if (!Objects.equals(userId, shoppingCart.getUserId())) {
            throw new BaseException("当前登录状态异常");
        }

        // 在执行删除操作前，检查商品状态并更新购物车状态
        Product productDB = productMapper.selectById(shoppingCart.getProductId());
        if (productDB == null) {
            shoppingCart.setStatus(PRODUCT_DELETED);
            shoppingCartMapper.updateById(shoppingCart);
            throw new BaseException("商品已删除");
        }
        if (productDB.getStock() <= 0) {
            shoppingCart.setStatus(PRODUCT_INSUFFICIENT_STOCK);
            shoppingCartMapper.updateById(shoppingCart);
            throw new BaseException("商品库存不足");
        } else if (productDB.getStatus() == PRODUCT_OFFLINE) {
            shoppingCart.setStatus(PRODUCT_OFFLINE);
            shoppingCartMapper.updateById(shoppingCart);
            throw new BaseException("商品已下架");
        }

        Integer quantity = shoppingCart.getQuantity();
        if (quantity == 1) {
            shoppingCartMapper.deleteById(id);
        } else {
            LambdaUpdateWrapper<ShoppingCart> updateWrapper = Wrappers.lambdaUpdate(ShoppingCart.class)
                    .set(ShoppingCart::getQuantity, quantity - 1)
                    .eq(ShoppingCart::getUserId, userId)
                    .eq(ShoppingCart::getProductId, shoppingCart.getProductId());
            shoppingCartMapper.update(updateWrapper);
        }
    }

    /**
     * 删除一条商品
     */
    @Override
    public void deleteById(Long id) {
        shoppingCartMapper.deleteById(id);
    }
}
